package com.x.common.security.config;

import cn.hutool.core.util.StrUtil;
import com.x.common.security.handler.XAccessDeniedHandler;
import com.x.common.security.handler.XAuthExceptionEntryPoint;
import com.x.common.security.properties.XCloudSecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @author 蔡朋宏
 */
@EnableResourceServer
@EnableAutoConfiguration(exclude = UserDetailsServiceAutoConfiguration.class)
public class XCloudResourceServerConfig extends ResourceServerConfigurerAdapter {

  private XCloudSecurityProperties properties;
  private XAccessDeniedHandler     xAccessDeniedHandler;
  private XAuthExceptionEntryPoint xAuthExceptionEntryPoint;

  @Autowired
  public void setProperties(XCloudSecurityProperties properties) {
    this.properties = properties;
  }

  @Autowired
  public void setAccessDeniedHandler(XAccessDeniedHandler xAccessDeniedHandler) {
    this.xAccessDeniedHandler = xAccessDeniedHandler;
  }

  @Autowired
  public void setExceptionEntryPoint(XAuthExceptionEntryPoint xAuthExceptionEntryPoint) {
    this.xAuthExceptionEntryPoint = xAuthExceptionEntryPoint;
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {
    String[] anonUrls = StrUtil.splitToArray(properties.getAnonUris(), ',');
    if (anonUrls.length == 0) {
      anonUrls = new String[]{};
    }

    http.csrf().disable()
        .requestMatchers().antMatchers(properties.getAuthUri())
        .and()
        .authorizeRequests()
        .antMatchers(anonUrls).permitAll()
        .antMatchers(properties.getAuthUri()).authenticated()
        .and()
        .httpBasic();
  }

  @Override
  public void configure(ResourceServerSecurityConfigurer resources) {
    resources.authenticationEntryPoint(xAuthExceptionEntryPoint)
        .accessDeniedHandler(xAccessDeniedHandler);
  }
}
